package com.qqtop10.manager.utils.oss;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class OSSUploadUtils {

	// private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
	private static final String KEY = "LTAIexJzO6L2sMjI";
	private static final String SECERT = "bxqH4TrQzCTaLo5tJ2zZrA4SKGGkyd";
	private static final String BUCKET = "top10mall";

	private final OSSClient client = new OSSClient(OSSFilePath.ENDPOINT, KEY, SECERT);
	//
	// public OSSUploadUtils() {
	// client =
	// }

	// 上传图片
	/**
	 * 
	 * @param fileKey
	 *            图片文件的指定文件夹及文件名 如shoplogo.jpg需要放在images/logo/文件夹下 则如此写：
	 *            /images/logo/shoplogo.jpg
	 * @param file
	 *            需要上传的图片文件流
	 * 
	 */
	public void uploadFile(final String fileKey, final MultipartFile file) {
		// new Thread(new Runnable() {
		// @Override
		// public void run() {
		try {
			if (file != null) {
				final InputStream input = file.getInputStream();
				client.putObject(BUCKET, fileKey, input);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// }
		// }).start();
	}

	public String uploadFile(String fileDir, String fileName, MultipartFile file) {
		String ret = "";
		try {
			if (file != null) {
				InputStream input = file.getInputStream();
				ObjectMetadata metadata = new ObjectMetadata();
				metadata.setContentLength(input.available());
				metadata.setCacheControl("no-cache");
				metadata.setHeader("Pragma", "no-cache");
				metadata.setContentDisposition("inline;filename=" + fileName);
				// 上传文件
				PutObjectResult putObjectResult = client.putObject(BUCKET, fileDir + fileName, input);
				ret = putObjectResult.getETag();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ret;
	}

	// 关闭OSS客户端
	public void closeOssClient() {
		if (client != null) {
			client.shutdown();
		}
	}

}
